package com.smartalarmclock.UI;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

import com.smartalarmclock.Logic.AcManager;
import com.smartalarmclock.UI.R;
import com.smartalarmclock.Model.IContact;
import com.smartalarmclock.Model.IProfile;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class CreateNewProfileActivity extends FragmentActivity implements IContactSelector {
	private boolean m_IsNew = true;
	private IProfile m_Profile = null;
	private HashMap<IContact, Boolean> m_Contacts;
	private static final String TAG = "CreateNewProfileActivity";

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.create_new_profile_screen);
	
	    final Button buttonSetContacts = (Button)findViewById(R.id.button_set_contacts);
	    final Button buttonSave = (Button)findViewById(R.id.button_create_new_profile);
	    final Button buttonDelete = (Button)findViewById(R.id.button_delete_profile);
	    final EditText editTextProfileName = (EditText)findViewById(R.id.editText_profile_name);
	    
	    // read extra messages sent to this activity intent
	    Bundle bundle = this.getIntent().getExtras();
	    if (null == bundle)
	    {
	    	throw new RuntimeException("CreateNewProfileActivity must have extras");
	    }
	    
	    Log.v(TAG, "Right before if(!m_IsNew) and the bundle.getBoolean...");
	    m_IsNew = bundle.getBoolean(Messages.PROFILE_DETAILS_IS_NEW);
	    if (!m_IsNew)
	    {
		    Log.v(TAG, "Clicked on existing profile!!!");

	    	int profileId = bundle.getInt(Messages.PROFILE_DETAILS_PROFILE_ID);
	    	// get profile name
	    	m_Profile = AcManager.GetInstance().GetProfileDetails(this, profileId);
	    	
	    	buttonSave.setText("Update");
	    }
	    else
	    {
	    	buttonSave.setText("Create");
	    }
	    
	    if (m_Profile != null)
	    {
	    	// set profile name in edit text
	    	editTextProfileName.setText(m_Profile.GetName());
	    }
	    
	    m_Contacts = new HashMap<IContact, Boolean>();
	    for (IContact contact : GetCurrentlySelectedContacts()) {
	    	m_Contacts.put(contact, true);
	    }
	    
	    // set listeners
	    editTextProfileName.addTextChangedListener(editTextProfileNameChangedListener);
	    buttonSave.setOnClickListener(buttonSaveOnClickListener);
	    buttonDelete.setOnClickListener(buttonDeleteOnClickListener);
	    buttonSetContacts.setOnClickListener(buttonSelectContactsOnClickListener);
	}
	
	private void ShowSelectContactsDialog() {
    	// Showing a dialog to select contacts
		SelectContactsDialogFragment contactsDialog = SelectContactsDialogFragment.NewInstance(true, true);
		contactsDialog.show(getSupportFragmentManager(), "Contacts");
    }
	
	private OnClickListener buttonSelectContactsOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			CreateNewProfileActivity.this.ShowSelectContactsDialog();
		}
	};
	
	private TextWatcher editTextProfileNameChangedListener = new TextWatcher() {
        public void afterTextChanged(Editable s) {
        	// TBD - check for valid profile name
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    };
	
	private OnClickSaveListener buttonSaveOnClickListener = new OnClickSaveListener(this);
	
	private class OnClickSaveListener implements OnClickListener {

		private Context m_Context = null;
		public OnClickSaveListener(Context context)
		{
			m_Context = context;
		}
		
		@Override
        public void onClick(View v)
        {
			Log.v(TAG, "Trying to save Ofer");
			final EditText editTextProfileName = (EditText)findViewById(R.id.editText_profile_name);
        	final String profileName = editTextProfileName.getText().toString();
        	
        	// if this is a new profile, create it in the DB
			if (m_IsNew)
			{
				// Create new profile
				// ToDo: fix stub
				m_Profile = AcManager.GetInstance().CreateNewProfile(m_Context, profileName);
			}
			else
			{			
				// update profile object's name
				m_Profile.SetName(profileName);
			}
        	
			for (Entry<IContact, Boolean> selectContactEntry : m_Contacts.entrySet()) {
				if (selectContactEntry.getValue()) {
					m_Profile.AddContact(CreateNewProfileActivity.this, selectContactEntry.getKey());
				}
				else {
					m_Profile.RemoveContact(CreateNewProfileActivity.this, selectContactEntry.getKey());
				}
			}
        	
			// update the profile
			AcManager.GetInstance().ModifyProfile(m_Context, m_Profile);
			
			// exit the activity
			finish();
		}
	}
	
	private OnClickDeleteListener buttonDeleteOnClickListener = new OnClickDeleteListener(this);
	
	private class OnClickDeleteListener implements OnClickListener {

		private Context m_Context = null;
		public OnClickDeleteListener(Context context)
		{
			m_Context = context;
		}
		
		@Override
        public void onClick(View v)
        {
			Log.v(TAG, "Trying to delete Ofer");
			
			if (m_Profile != null)
			{
				// delete the profile
				AcManager.GetInstance().DeleteProfile(m_Context, m_Profile);
			}
			
			// exit the activity
			finish();
		}
	}
	
	@Override
	public Set<IContact> GetCurrentlySelectedContacts() {
		if (m_Profile != null) {
			return m_Profile.GetContacts(this);
		}
		
		// If profile does not exist yet, no contacts are selected. Returning empty set
		return new HashSet<IContact>();
	}

	@Override
	public void OnSelected(Set<IContact> selectedContacts) {
		// "Removing" all current contacts by setting their value to false
		// We need to save the removed contacts so we can remove them from the profile.
		for (Entry<IContact, Boolean> contactEntry : m_Contacts.entrySet()) {
			contactEntry.setValue(false);
		}
		
		for (IContact contact : selectedContacts) {
			if (m_Contacts.containsKey(contact)) {
				m_Contacts.remove(contact);
			}
			m_Contacts.put(contact, true);
		}
	}

	@Override
	public void OnCanceled() { }
}